﻿using System;
using System.Collections.Generic;
using System.Linq;
using IQToolkit;
using IQToolkit.Data;
using Infrastucture.Factories;
using TimeSplicerModule.DataModels;
using TimeSplicerModule.DomainModels;

namespace TimeSplicerModule.Factories
{
    public interface IScheduledTaskFactory : Infrastucture.Factories.IFactory<ScheduledTaskDataModel, ScheduledTaskModel>
    { }

    public class ScheduledTaskFactory : Factory<ScheduledTaskDataModel, ScheduledTaskModel>, IScheduledTaskFactory
    {
        public ScheduledTaskFactory(DbEntityProvider provider, IEntityTable<ScheduledTaskDataModel> db)
            : base(provider, db)
        {

        }

        public override ScheduledTaskModel Add(ScheduledTaskModel obj)
        {
            var existing = this.Get(x => x.TaskInstanceGuid == obj.TaskInstanceGuid);
            var previous = this.GetList(x => x.ScheduleGuid == obj.ScheduleGuid);

            if (previous != null && previous.Count >0)
            {
                var last = previous.OrderByDescending(o => o.InstanceNumber).FirstOrDefault();
                obj.InstanceNumber = last.InstanceNumber + 1;
            }

            if (existing == null)
                return base.Add(obj);
            else
            {
                obj.ScheduledTaskGuid = existing.ScheduledTaskGuid;
                return this.Save(obj);
            }
        }
    }
}
